package com.example.tliasfight.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.tliasfight.pojo.Result;
import com.example.tliasfight.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
//定义拦截器
public class loginCheckInterceptor implements HandlerInterceptor
{
    @Override//放行前逻辑。是返回true时，放行，返回false时，是拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的url
     //   HttpServletRequest req =(HttpServletRequest)servletRequest;
      //  HttpServletResponse resp=(HttpServletResponse)servletResponse;
        String url=request.getRequestURI().toString();

        //判断url是否含login
        if(url.contains("login"))
        {
            log.info("这是一次登录请求");
           // filterChain.doFilter(servletRequest,servletResponse);
            return true;
        }
        else//不是登录请求，就看一下另外是否能被成功解析
        {
            //看看请求的token是否携带jwt令牌
            String value=request.getHeader("token");
            if(value == null|| value.equals(""))
            {
                log.info("请求头里面没有jwt令牌，说明是直接复制网页地址的,没有正常的登录");
                Result error=Result.error("NOT_LOGIN");
                String jsonString = JSONObject.toJSONString(error);
                response.getWriter().write(jsonString);
                return false;
            }
            log.info("请求头里面有jwt令牌，开始解析");
            try {
                JwtUtils.parseJwt(request.getHeader("token"));
                //filterChain.doFilter(servletRequest,servletResponse);
               return true;
            } catch (Exception e) {
                e.printStackTrace();
                log.info("解析令牌失败，可能篡改了也可能过期了");
                Result error=Result.error("NOT_LOGIN");
                String jsonString = JSONObject.toJSONString(error);
                response.getWriter().write(jsonString);
                return false;


            }
        }



    }

    @Override//目标资源运行后，执行---->可能是放行后逻辑，不是很确定
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       // log.info("postHandle...");
    }

    @Override//视图渲染完毕后运行。是最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     //   log.info("afterCompletion...");
    }
}
